export class StorageManager {
  constructor() {
    this.storage = chrome.storage.local;
  }

  async get(keys) {
    return new Promise((resolve, reject) => {
      this.storage.get(keys, (result) => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
        } else {
          resolve(result);
        }
      });
    });
  }

  async set(data) {
    return new Promise((resolve, reject) => {
      this.storage.set(data, () => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
        } else {
          resolve();
        }
      });
    });
  }

  async remove(keys) {
    return new Promise((resolve, reject) => {
      this.storage.remove(keys, () => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
        } else {
          resolve();
        }
      });
    });
  }

  async clear() {
    return new Promise((resolve, reject) => {
      this.storage.clear(() => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
        } else {
          resolve();
        }
      });
    });
  }

  // 会话特定的存储操作
  async getSessionData(sessionId, key) {
    const storageKey = `session_${sessionId}_${key}`;
    const result = await this.get(storageKey);
    return result[storageKey] || {};
  }

  async setSessionData(sessionId, key, data) {
    const storageKey = `session_${sessionId}_${key}`;
    await this.set({ [storageKey]: data });
  }

  async removeSessionData(sessionId, key) {
    const storageKey = `session_${sessionId}_${key}`;
    await this.remove(storageKey);
  }

  // Cookie管理
  async getSessionCookies(sessionId, domain) {
    const cookies = await this.getSessionData(sessionId, 'cookies');
    return cookies[domain] || [];
  }

  async setSessionCookies(sessionId, domain, cookies) {
    const allCookies = await this.getSessionData(sessionId, 'cookies');
    allCookies[domain] = cookies;
    await this.setSessionData(sessionId, 'cookies', allCookies);
  }

  // LocalStorage管理
  async getSessionLocalStorage(sessionId, domain) {
    const localStorage = await this.getSessionData(sessionId, 'localStorage');
    return localStorage[domain] || {};
  }

  async setSessionLocalStorage(sessionId, domain, data) {
    const allLocalStorage = await this.getSessionData(sessionId, 'localStorage');
    allLocalStorage[domain] = data;
    await this.setSessionData(sessionId, 'localStorage', allLocalStorage);
  }

  // SessionStorage管理
  async getSessionSessionStorage(sessionId, domain) {
    const sessionStorage = await this.getSessionData(sessionId, 'sessionStorage');
    return sessionStorage[domain] || {};
  }

  async setSessionSessionStorage(sessionId, domain, data) {
    const allSessionStorage = await this.getSessionData(sessionId, 'sessionStorage');
    allSessionStorage[domain] = data;
    await this.setSessionData(sessionId, 'sessionStorage', allSessionStorage);
  }
} 